package server;

import container.Host;
import container.Mapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import util.MyRequestProcessor;
import util.StandardClassLoader;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class V4BootStrap {

    /**定义socket监听的端口号*/
    private int port;



    public Map<String, HttpServlet> getServletMap() {
        return servletMap;
    }

    public void setServletMap(Map<String, HttpServlet> servletMap) {
        this.servletMap = servletMap;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();



    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        String serverDir = "E:/javaProPrograme/Session2/Session1-tomcat-nginx/Minicat/src/main/resources/server.xml";
        Mapper mapper = loadServer(new File(serverDir));

        for (String hostName:mapper.getHostMap().keySet()){
            Host host = mapper.getHostMap().get(hostName);
            loadHost( host);
        }



        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {
            Socket socket = serverSocket.accept();
            MyRequestProcessor requestProcessor = new MyRequestProcessor(socket,mapper);
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    public void loadHost(Host host){
        // 加载解析相关的配置，web.xml
        String baseDir = host.getBaseDir();
        final String CONFIG_NAME = "web.xml";
        File baseDirFolder = new File(baseDir);
        if(baseDirFolder.exists()&&baseDirFolder.isDirectory()){
            File[] folders = baseDirFolder.listFiles();
            for(File folder:folders){
                File[] files = folder.listFiles();
                for(File file:files){
                    if(file.isFile()&& file.getName().toLowerCase().equals(CONFIG_NAME)){
                        System.out.println("加载配置文件："+file.getAbsolutePath());
                        Map<String,HttpServlet> tempMap = loadServlet(file);
                        host.getServletMap().putAll(tempMap);
                    }
                }
            }
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private Map<String,HttpServlet> loadServlet(File filePath) {
        Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(filePath);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                StandardClassLoader classLoader = new StandardClassLoader(filePath.getParentFile().getAbsolutePath());
                servletMap.put(urlPattern, (HttpServlet) classLoader.loadClass(servletClass).getDeclaredConstructor().newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return servletMap;
    }


    /**
     *
     */
    private Mapper loadServer(File file) {

        Mapper mapper = new Mapper();
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(file);
            Element rootElement = document.getRootElement();


            Element connector = (Element)rootElement.selectSingleNode("//Connector");
            String connectPort = connector.attributeValue("port");
            //设置端口号
            this.setPort(new Integer(connectPort));

            List<Element> hostNodes = connector.selectNodes("//Host");

            for (int i = 0; i < hostNodes.size(); i++) {
                Element hostNode = hostNodes.get(i);
                String name = hostNode.attributeValue("name");
                String baseDir = hostNode.attributeValue("appBase");
                Host host = new Host(name,baseDir);
                mapper.getHostMap().put(name,host);
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return mapper;
    }




    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        V4BootStrap bootstrap = new V4BootStrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
